package com.tuocent.dagv2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuocent.dagv2.common.AjaxResult;
import com.tuocent.dagv2.common.entity.ArchivesRetrospectData;
import com.tuocent.dagv2.common.utils.SnowFlakeID;
import com.tuocent.dagv2.common.utils.redis.RedisCache;
import com.tuocent.dagv2.constant.PublicConst;
import com.tuocent.dagv2.entity.*;
import com.tuocent.dagv2.mapper.ArchivesInfoMapper;
import com.tuocent.dagv2.service.IArchivesInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tuocent.dagv2.service.IFieldConfigService;
import com.tuocent.dagv2.service.IProjectsService;
import com.tuocent.dagv2.service.ITaskService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.util.*;
import java.util.function.Consumer;

import static com.tuocent.dagv2.common.utils.PublicUtil.sortMap;

/**
 * <p>
 * 档案加工信息 服务实现类
 * </p>
 *
 * @author Vincent
 * @since 2025-09-16
 */
@Service
public class ArchivesInfoServiceImpl extends ServiceImpl<ArchivesInfoMapper, ArchivesInfo> implements IArchivesInfoService {
    @Resource
    private RedisCache redis;
    @Resource
    private SnowFlakeID snowFlakeID;
    @Autowired
    private IProjectsService projectsService;
    @Autowired
    private ITaskService taskService;
    @Autowired
    private IFieldConfigService fieldConfigService;

    @Override
    public String archivesRetrospect(Model model) {
        List<Projects> projectsList = projectsService.list(new QueryWrapper<Projects>().eq("is_del", "0"));
        model.addAttribute("projectsList", projectsList);
        return "/archives/archivesRetrospect";
    }

    @Override
    public AjaxResult getArchivesRetrospectData(Map<String, Object> param) {
        int limit = (int) param.getOrDefault("limit", PublicConst.DEF_LIMIT);
        int page = (int) param.getOrDefault("page", PublicConst.DEF_PAGE);
        String value = param.getOrDefault("value", "").toString();
        String pid = param.getOrDefault("pid", "").toString();
        String tid = param.getOrDefault("tid", "").toString();
        QueryWrapper qw = new QueryWrapper<>()
                .eq("b.is_del", 0);
        for (String key : param.keySet()) {
            String v = param.getOrDefault(key, "").toString();
            if (v.isEmpty()) {
                continue;
            }
            switch (key) {
                case "limit":
                case "page":
                    break;
                case "pid":
                    qw.eq("b.pid", pid);
                    break;
                case "tid":
                    qw.eq("b.tid", tid);
                    break;
                case "procedures":
                    qw.eq("a." + v, "0");
                    break;
                default:
                    qw.like(key, v);
                    break;
            }
        }

        //取项目任务信息
        Task task = taskService.getOne(new QueryWrapper<Task>().eq("pid", pid).eq("id", tid));
        if (task == null) {
            return AjaxResult.error("没有找到相应的任务");
        }

        //获取字段配置
        List<FieldConfig> fieldsList = fieldConfigService.getFieldConfig(task.getArchivesClassifyId(), task.getFillingModel());
        Map<String, String> fastsearch = new HashMap<>();
        Map<String, Integer> sort = new HashMap<>();
        Collection<String> mixSort = new ArrayList<>();
        //获取排序、检索字段
        for (FieldConfig filed : fieldsList) {
            if ("1".equals(filed.getIsSort())) {
                int dix = 999;
                if (filed.getSortIdx() != null) {
                    dix = filed.getSortIdx();
                }
                sort.put(filed.getFieldName(), dix);
            }
            if ("1".equals(filed.getIsmixSort())) {
                mixSort.add(filed.getFieldName());
            }
            if ("1".equals(filed.getIsFastsearch())) {
                fastsearch.put(filed.getFieldName(), filed.getIsVaguesearch());
            }
        }

        //检索,如果没有可快速查询字段，侧返回空值
        if (!"".equals(value)) {
            if (fastsearch.isEmpty()) {
                qw.eq("id", "");
            } else {
                String finalValue = value;
                Consumer<QueryWrapper<ArchivesRecord>> wrapper = new Consumer<QueryWrapper<ArchivesRecord>>() {
                    @Override
                    public void accept(QueryWrapper<ArchivesRecord> archivesFilesQueryWrapper) {
                        for (String key : fastsearch.keySet()) {
                            if ("1".equals(fastsearch.get(key))) {
                                archivesFilesQueryWrapper.or().like(key, finalValue);
                            } else {
                                archivesFilesQueryWrapper.or().eq(key, finalValue);
                            }
                        }
                    }
                };
                qw.and(wrapper);
            }
        }

        //排序
        if (!sort.isEmpty()) {
            Map<String, Integer> sortField = sortMap(sort);
            for (String key : sortField.keySet()) {
                if (mixSort.contains(key)) {
                    qw.orderByAsc("length(" + key + ")," + key);
                } else {
                    qw.orderByAsc(key);
                }
            }
        }

        String tableName = "db_archives_files";
        if ("1".equals(task.getFillingModel())) {
            tableName = "db_archives_record";
        }

        Page data = getBaseMapper().getArchivesRetrospectData(new Page<>(page, limit), qw, tableName);
        return AjaxResult.success(data.getRecords(), data.getTotal());
    }
}
